package com.jsaas.sys.service;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;

import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.redis.Redis;
import com.jsaas.common.Constant;
import com.jsaas.core.captcha.render.MyCaptchaRender;
import com.jsaas.core.security.CaptchaUsernamePasswordToken;
import com.jsaas.model.User;
import com.jsaas.utils.MyUtils;
import com.jsaas.utils.ShiroUtils;

/**   
 * @Title: LoginService.java 
 * @Package com.jsaas.sys.service 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @author tuozq 
 * @date 2017年11月3日 下午4:45:18 
 * @version V1.0   
 */
public class LoginService {
	
	public Ret doLogin(String account, String password, String captcha, Controller controller){
		Subject subject = SecurityUtils.getSubject();
		if(!subject.isAuthenticated()){
			if(MyUtils.isEmpty(account) || MyUtils.isEmpty(password)){
				return Ret.fail().set("msg", "账号或密码不能为空！");
			}
			
			boolean isCaptcha = false;
			
			if(isCaptcha && !MyCaptchaRender.validate(controller, captcha)){
				return Ret.fail().set("msg", "验证码错误！");
			}
			
			SqlPara sqlPara = Db.getSqlPara("user.findUser", Kv.by("account", account));
			User user = User.dao.findFirst(sqlPara);
			if(MyUtils.isNull(user)){
				return Ret.fail().set("msg", "账号不存在！");
			}
			CaptchaUsernamePasswordToken token = new CaptchaUsernamePasswordToken(account, password); 
			try {
				subject.login(token);
			} catch (IncorrectCredentialsException e) {
				// TODO: handle exception
				return Ret.fail().set("msg", "账号密码不匹配！");
			}

		}
		return Ret.ok();
	}
	
	/**
	 * 退出登陆
	 */
	public void doLogout(){
		if(ShiroUtils.isLogin()){
			String userId = ShiroUtils.getCurUser().getUserId();
			//删除用户权限缓存
			Redis.use(Constant.COMMON_CACHE).del(UserService.USER_PERMISSION_CACHE + userId);
			//删除用户菜单缓存
			Redis.use(Constant.COMMON_CACHE).del(UserService.USER_MENU_CACHE + userId);
			//退出登录
			SecurityUtils.getSubject().logout();
		}
	}
}
